<?php

#-------------------------------------------------------------------------------
# Allows a form of inheritance for template files.
# If a file does not exist in the chosen template, the
# default is used. Cuts down on code duplication.
function template ($name)
{
   $fn = "../templates/$name";

   if (file_exists($fn)) {
      return $fn;
   }
}

#-------------------------------------------------------------------------------
# Return a version of the string which is safe for display on a web page.
# Potentially dangerous characters are converted to HTML entities.  
# Resulting string is not URL-encoded.
function clean_string( $string )
{
  return htmlentities( $string );
}
#-------------------------------------------------------------------------------
function sanitize ( $string ) {
  return  escapeshellcmd( clean_string( rawurldecode( $string ) ) ) ;
}

#-------------------------------------------------------------------------------
# If arg is a valid number, return it.  Otherwise, return null.
function clean_number( $value )
{
  return is_numeric( $value ) ? $value : null;
}

#-------------------------------------------------------------------------------
# Return true if string is a 3 or 6 character hex color.  Return false otherwise.
function is_valid_hex_color( $string )
{
  $return_value = false;
  if( strlen( $string ) == 6 || strlen( $string ) == 3 ) {
    if( preg_match( '/^[0-9a-fA-F]+$/', $string ) ) {
      $return_value = true;
    }
  }
  return $return_value;
}

function get_string_from_get($opt) {
  return isset($_GET[$opt]) ? sanitize($_GET[$opt]):NULL;
}

function get_number_from_get($opt) {
  return isset($_GET[$opt]) ? clean_number(sanitize($_GET[$opt])) : NULL;
}

function getDirEntryList($dir)
{
  $mydir = opendir($dir);
  $dirArray = array();
  while ($entryname = readdir($mydir)) {
    if ($entryname != "." and $entryname != "..") {
      $dirArray[]=$entryname;
    }
  }
  closedir($mydir);
  return $dirArray;
}

function genSelectList ($tpl, $blockname, $select, $selected, $display)
{
  foreach ($select as $opt) {
    $tpl->newBlock("$blockname");
    $tpl->assign("value", $opt);
    if ($display != NULL && array_key_exists($opt, $display)) {
      $tpl->assign("name", $display[$opt]);
    } else {
      $tpl->assign("name", $opt);
    }
    if ($selected == $opt) {
      $tpl->assign("select", "SELECTED");
    }
  }
}

?>
